package com.example.lenovo.weiyi;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.com.ruanmeng.demon.ServiceM;
import com.com.ruanmeng.demon.SureDDM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import adapter.BaseLoadMoreHeaderAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;

/**
 * 新的购买服务
 */
public class NewPayServiceActivity extends BaseActivity {

    @BindView(R.id.rlist_service)
    RecyclerView rlistService;
    @BindView(R.id.tv_service_allprice)
    TextView tvServiceAllprice;
    @BindView(R.id.tv_service_ok)
    TextView tvServiceOk;
    private LinearLayout li_service_null;
    private int page = 1;
    ArrayList<ServiceM.RowsBean> Temp_list = new ArrayList<>();
    ArrayList<ServiceM.RowsBean> Temp_GWC = new ArrayList<>();
    private ServiceListAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ButterKnife.bind(this);
        ChangLayTitle("购买服务");
        AddActivity(this);
        LayBack();
        ShowLayService();
        init();
        getServiceData(true);
    }

    public void init() {
        //空
        li_service_null = (LinearLayout) findViewById(R.id.li_service_null);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rlistService.setLayoutManager(linearLayoutManager);
        mAdapter = new ServiceListAdapter(NewPayServiceActivity.this, rlistService, Temp_list, R.layout.item_new_service);
        rlistService.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseLoadMoreHeaderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

            }
        });
        mAdapter.setOnLoadMoreListener(new BaseLoadMoreHeaderAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
            }
        });
    }

    /**
     * 获取服务列表
     */
    public void getServiceData(Boolean b) {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.BuyService, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(NewPayServiceActivity.this, "uid"));
        // 添加到请求队列
        CallServer.getRequestInstance().add(NewPayServiceActivity.this, 0, mRequest,
                new CustomHttpListener(NewPayServiceActivity.this, true, ServiceM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        ServiceM model = ((ServiceM) data);
                        if (page == 1) {
                            Temp_list.clear();
                        }
                        Temp_list.addAll(model.getRows());
                        mAdapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        if (!("100").equals(obj.getString("msgcode"))) {
                            CommonUtil.showToask(NewPayServiceActivity.this, obj.getString("msg"));
                        }
                        if (Temp_list.size() == 0) {
                            li_service_null.setVisibility(View.VISIBLE);
                            rlistService.setVisibility(View.GONE);
                        }

                    }
                }, true, b);
    }

    /**
     * 提交订单
     */
    public void getTiJiaoData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.TiJiao, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(NewPayServiceActivity.this, "uid"));
        mRequest.add("productIds", getId_num());
        // 添加到请求队列
        CallServer.getRequestInstance().add(NewPayServiceActivity.this, 0, mRequest,
                new CustomHttpListener(NewPayServiceActivity.this, true, SureDDM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        SureDDM model = ((SureDDM) data);
                        Bundle map = new Bundle();
                        map.putSerializable("gwc_list", Temp_GWC);
                        Intent in = new Intent(NewPayServiceActivity.this, SureDDActivity.class);
                        in.putExtras(map);
                        in.putExtra("orderId", model.getObject());
                        startActivity(in);
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        if (!("100").equals(obj.getString("msgcode"))) {
                            CommonUtil.showToask(NewPayServiceActivity.this, obj.getString("msg"));
                        }
                        if (Temp_list.size() == 0) {
                            li_service_null.setVisibility(View.VISIBLE);
                            rlistService.setVisibility(View.GONE);
                        }

                    }
                }, true, true);
    }


    public class ServiceListAdapter extends BaseLoadMoreHeaderAdapter<ServiceM.RowsBean> {


        public ServiceListAdapter(Context mContext, RecyclerView recyclerView, List<ServiceM.RowsBean> mDatas, int mLayoutId) {
            super(mContext, recyclerView, mDatas, mLayoutId);
        }

        @Override
        public void convert(Context mContext, final RecyclerView.ViewHolder holder, final ServiceM.RowsBean s) {
            TextView name = (TextView) holder.itemView.findViewById(R.id.tv_service_name);
            TextView price = (TextView) holder.itemView.findViewById(R.id.tv_service_price);
            final TextView num = (TextView) holder.itemView.findViewById(R.id.tv_service_num);
            LinearLayout add = (LinearLayout) holder.itemView.findViewById(R.id.iv_self_jia);
            final LinearLayout jian = (LinearLayout) holder.itemView.findViewById(R.id.iv_self_jian);
            name.setText(s.getTitle());
            price.setText(s.getPrice() + "元/次");
            if (s.getNum() > 0) {
                num.setVisibility(View.VISIBLE);
                jian.setVisibility(View.VISIBLE);
                num.setText(s.getNum() + "");
            } else {
                num.setVisibility(View.GONE);
                jian.setVisibility(View.GONE);
                num.setText("");
            }
            View li_ban = (View) holder.itemView.findViewById(R.id.view_service_ban);
            LinearLayout li_man = (LinearLayout) holder.itemView.findViewById(R.id.li_service_man);
            if (holder.getLayoutPosition() == Temp_list.size() - 1) {
                li_man.setVisibility(View.GONE);
            } else {
                li_man.setVisibility(View.VISIBLE);
            }
            add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Temp_list.get(holder.getLayoutPosition()).setNum(Temp_list.get(holder.getLayoutPosition()).getNum() + 1);
                    num.setVisibility(View.VISIBLE);
                    jian.setVisibility(View.VISIBLE);
                    num.setText(s.getNum() + "");
                    getAllPrice();
                }
            });
            jian.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Temp_list.get(holder.getLayoutPosition()).getNum() > 0) {
                        Temp_list.get(holder.getLayoutPosition()).setNum(Temp_list.get(holder.getLayoutPosition()).getNum() - 1);
                        if (Temp_list.get(holder.getLayoutPosition()).getNum() > 0) {
                            num.setVisibility(View.VISIBLE);
                            jian.setVisibility(View.VISIBLE);
                            num.setText(Temp_list.get(holder.getLayoutPosition()).getNum() + "");
                        } else {
                            num.setVisibility(View.GONE);
                            jian.setVisibility(View.GONE);
                            num.setText("");
                        }
                        getAllPrice();
                    }

                }
            });
        }
    }

    public void doClick(View v) {
        switch (v.getId()) {
            case R.id.tv_lay_service://我的服务
                Intent in = new Intent(NewPayServiceActivity.this, MyServiceActivity.class);
                startActivity(in);
                break;
            case R.id.tv_service_ok://提交订单
                if (("0.00").equals(tvServiceAllprice.getText().toString()) || ("0.0").equals(tvServiceAllprice.getText().toString())) {
                    CommonUtil.showToask(NewPayServiceActivity.this, "请选择您要购买的服务！");
                    return;
                }
                getTiJiaoData();
                break;
        }

    }

    /**
     * 获取总价
     */
    public void getAllPrice() {
        Temp_GWC.clear();
        double allprice = 0.00;
        for (int i = 0; i < Temp_list.size(); i++) {
            if (Temp_list.get(i).getNum() > 0) {
                Temp_GWC.add(Temp_list.get(i));
                allprice += Temp_list.get(i).getNum() * Double.parseDouble(Temp_list.get(i).getPrice());
            }
        }
        BigDecimal bg = new BigDecimal(allprice);
        double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tvServiceAllprice.setText(f1 + "");
    }

    /**
     * 获取id
     */
    public String getId_num() {
        String ids = "";
        StringBuilder buffer = new StringBuilder("");
        for (int i = 0; i < Temp_list.size(); i++) {
            if (Temp_list.get(i).getNum() > 0) {
                buffer.append(Temp_list.get(i).getProductId() + "_" + Temp_list.get(i).getNum());
                buffer.append(",");
            }
        }
        ids = buffer.toString();
        if (ids.endsWith(",")) {
            ids = buffer.toString().substring(0, ids.length() - 1);
        }
        return ids;
    }
}
